package com.coinland.study.view.download;


import android.util.Log;

import com.coinland.study.base.BasePresenter;

import com.coinland.study.util.FileUtil;


import java.io.File;
import java.io.IOException;
import java.io.InputStream;

import okhttp3.ResponseBody;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action1;
import rx.functions.Func1;
import rx.schedulers.Schedulers;

/**
 * 类描述:
 * 创建人:  shenZ
 * 创建时间: 2020/4/13
 * 联系方式: 252079249@qq.com
 * 修改时间: 2020/4/13
 */
public class DownloadPresenter extends BasePresenter<DownloadContract.View> implements DownloadContract.Presenter {

    private final String TAG = DownloadPresenter.this.getClass().getSimpleName();

    private DownloadModel model;

    public DownloadPresenter() {
        model = new DownloadModel();
    }

    @Override
    public void downFile(String url, File savaPath,Subscriber subscriber) {

        model.download(url, downloadListener)
                .subscribeOn(Schedulers.io())
                .unsubscribeOn(Schedulers.io())
                .map(new Func1<ResponseBody, InputStream>() {
                    @Override
                    public InputStream call(ResponseBody responseBody) {
                        return responseBody.byteStream();
                    }
                })
                .observeOn(Schedulers.computation()) // 用于计算任务
                .doOnNext(new Action1<InputStream>() {
                    @Override
                    public void call(InputStream inputStream) {
                        try {
                            FileUtil.writeFile(inputStream, savaPath);
                        } catch (IOException e) {
                            downloadListener.onFail(e.getMessage());
                            Log.e("DownloadPresenter", e.getMessage());
                        }
                    }
                })
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(subscriber);
    }


    JsDownloadListener downloadListener = new JsDownloadListener() {
        @Override
        public void onStartDownload(int length) {
//            mView.setMax(length);
            Log.e(TAG,"下载总进度："+length);
            mView.showLoading();
        }

        @Override
        public void onProgress(int progress) {
//            mView.downLoading(progress);
            Log.e(TAG,"下载进度："+progress);
        }

        @Override
        public void onFail(String errorInfo) {
//            mView.downFial();
            Log.e(TAG,"下载失败："+errorInfo);
        }
    };

}
